package com.ivan.service;

import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.ivan.domain.Account;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("accountService")
@Transactional
public class AccountService {
	
	protected static Logger logger = Logger.getLogger("service");
	
	
	@Resource(name="sessionFactory")
	private SessionFactory sessionFactory;
	
	public List<Account> getAllAccounts() {
		  logger.debug("Retrieving all persons");
		  Session session = sessionFactory.getCurrentSession();
		  Query query = session.createQuery("FROM com.ivan.domain.Account");
		  return  query.list();  
	}
	
	public Account getAccount(int accountid) {  
		  logger.debug("Retrieving account of "+ accountid);
		  Session session = sessionFactory.getCurrentSession();
		  
		  Account person = (Account) session.get(Account.class, accountid); 
		  return person; 
	}
	
	public void add(Account account) {
		  logger.debug("Adding new account");
		  Session session = sessionFactory.getCurrentSession();
		  session.save(account); 
    }
	
	public void delete(Integer id) {
		  logger.debug("Deleting account with id of "+id);
		  Session session = sessionFactory.getCurrentSession();
		  Account person = (Account) session.get(Account.class, id);
		  session.delete(person);
	}
	
	public void edit(Account account) {
		  logger.debug("Editing existing account");
		  Session session = sessionFactory.getCurrentSession();
		  Account existingAccount = (Account) session.get(Account.class, account.getAccountid());
		  existingAccount.setUsername(existingAccount.getUsername());
		  existingAccount.setPassword(existingAccount.getPassword());
		  session.save(existingAccount);
	 }




}
